<template>
  <el-dialog
    width="80%"
    v-model="formVisible"
    title="新增任务"
    @close="formCancel"
  >
    <el-form
      ref="ruleFormRef"
      :model="form"
      :rules="rules"
      label-width="auto"
      class="demo-ruleForm"
      status-icon
    >
      <el-row :gutter="40" style="width: 100%">
        <el-col :span="12">
          <el-form-item label="任务名称" prop="taskName">
            <ElInput
              v-model="form.taskName"
              placeholder="请输入"
              class="select"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="社会组织" prop="sorgId">
            <div class="select">
              <el-select-v2
                v-model="form.sorgId"
                :options="riskNameOptions"
                placeholder="请选择"
                class="select"
                filterable
                @change="change"
                popper-append-to-body
                popper-class="selectV2"
              />
            </div>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="任务来源" prop="source">
            <MSelect
              v-model="form.source"
              placeholder="请选择"
              :options="sourceOptions"
              class="select"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="牵头部门（单位)" prop="leadDeptId">
            <div class="select">
              <!--<MTreeSelect-->
              <!--  v-model="form.leadDeptId"-->
              <!--  placeholder="请选择"-->
              <!--  :data="leadDeptIdOptions"-->
              <!--  style="width: 100%"-->
              <!--  :check-strictly="true"-->
              <!--  :props="{-->
              <!--    value: 'deptId',-->
              <!--    label: 'deptName',-->
              <!--    children: 'children'-->
              <!--  }"-->
              <!--/>-->
              <VirtualTreeDropDown
                v-model="form.leadDeptId"
                :options="leadDeptIdOptions"
              />
            </div>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="有效时间" prop="time">
            <div class="select" style="display: flex">
              <el-date-picker
                v-model="form.time"
                type="datetimerange"
                startPlaceholder="开始时间"
                endPlaceholder="结束时间"
                placeholder="请选择"
                format="YYYY-MM-DD"
                dateFormat="YYYY-MM-DD"
                valueFormat="YYYY-MM-DD"
              />
            </div>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="责任部门（单位)" prop="respDeptId">
            <div class="select">
              <!--<MTreeSelect-->
              <!--  v-model="form.respDeptId"-->
              <!--  placeholder="请选择"-->
              <!--  :data="leadDeptIdOptions"-->
              <!--  style="width: 100%"-->
              <!--  :check-strictly="true"-->
              <!--  :props="{-->
              <!--    value: 'deptId',-->
              <!--    label: 'deptName',-->
              <!--    children: 'children'-->
              <!--  }"-->
              <!--/>-->
              <VirtualTreeDropDown
                v-model="form.respDeptId"
                :options="leadDeptIdOptions"
              />
            </div>
          </el-form-item>
        </el-col>

        <el-col :span="12">
          <el-form-item label="风险类别" prop="riskType">
            <MSelect
              v-model="form.riskType"
              placeholder="请选择"
              :options="riskTypeOptions"
              class="select"
            />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="佐证材料" prop="files">
            <MBackingMaterial
              v-model="form.files"
              dateFormat="YYYY-MM-DD HH:mm"
            />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="任务说明" prop="remark">
            <el-input
              v-model="form.remark"
              :rows="2"
              type="textarea"
              placeholder="请输入处理情况"
              input-style="height: 200px"
            />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <template #footer>
      <div style="display: flex; justify-content: flex-end; width: 100%">
        <el-button @click="cancel">取消</el-button>
        <el-button type="primary" @click="submitForm" v-loading="loading">
          确定
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import { nextTick, onMounted, reactive, ref } from 'vue'
import { Plus } from '@element-plus/icons-vue'
import { newDeptTreeInfoAll } from '@/api/systemSetting/personnel'
import VirtualTreeDropDown from './compenents/virtualTreeDropDown/virtualTreeDropDown.vue'
import {
  getManagerChild,
  getType,
  handlerAdd,
  handlerDetail,
  handlerUpd,
  riskAddOrUpd,
  sorgList
} from '@/api/spotCheck/spotCheck'
import { ElMessage, ElMessageBox } from 'element-plus'
import { dateFormat } from '@/utils'
const formVisible = ref(false)
const leadDeptIdOptions = ref([])
const riskNameOptions = ref([])
const riskTypeOptions = ref([])
const sourceOptions = ref([
  {
    value: 1,
    label: '数据比对'
  },
  {
    value: 2,
    label: '年度检查'
  },
  {
    value: 3,
    label: '抽查检查'
  },
  {
    value: 4,
    label: '审计巡视巡查'
  },
  {
    value: 5,
    label: '网络舆情'
  },
  {
    value: 6,
    label: '其他'
  }
])
// 0 民办非企业 riskMingBan 1 社会团体 riskSheTuan
const riskTypeOptionsObj = ref({
  riskMingBan: [],
  riskSheTuan: []
})
const emit = defineEmits(['reload'])
const tree = ref({})
onMounted(async () => {
  newDeptTreeInfoAll().then((res) => {
    leadDeptIdOptions.value = res.data
    setTree(res.data)
  })
  //问题类型
  // getManagerChild('theTypeOfProblemRisk').then((res) => {
  //   riskTypeOptions.value = res.data.map((i) => ({
  //     value: i.name,
  //     label: i.name,
  //     riskLevel: i.relationParameterName
  //   }))
  // })
  let res = await sorgList()
  riskNameOptions.value = res.data.map((i) => ({
    value: i.sorgInfoId,
    label: i.orgName,
    types: i.types
  }))
  const riskMingBan = await getManagerChild('riskMingBan')
  riskTypeOptionsObj.value.riskMingBan = riskMingBan.data.map((i) => ({
    value: i.name,
    label: i.name,
    riskLevel: i.relationParameterName
  }))

  const riskSheTuan = await getManagerChild('riskSheTuan')
  riskTypeOptionsObj.value.riskSheTuan = riskSheTuan.data.map((i) => ({
    value: i.name,
    label: i.name,
    riskLevel: i.relationParameterName
  }))
})

const setTree = (arr) => {
  if (Array.isArray(arr) && arr.length > 0) {
    arr.forEach((i) => {
      tree.value[i.deptId] = {
        value: i.deptId,
        label: i.deptName
      }
      setTree(i.children)
    })
  }
}

const change = (e) => {
  console.log('e=>', e, riskTypeOptionsObj.value)
  let arr = []
  if (riskNameOptions.value.some((i) => i.value == e)) {
    let type = riskNameOptions.value.find((i) => i.value === e).types
    if (type === 0) {
      riskTypeOptions.value = riskTypeOptionsObj.value.riskMingBan
    } else {
      riskTypeOptions.value = riskTypeOptionsObj.value.riskSheTuan
    }
  }
}

//新增
const form = reactive({
  files: [],
  taskName: undefined,
  leadDeptId: undefined,
  source: undefined,
  respDeptId: undefined,
  time: undefined,
  riskType: undefined,
  remark: undefined,
  sorgId: undefined
})

const rules = ref({
  name: [{ required: true, message: '请输入', trigger: 'change' }],
  taskName: [{ required: true, message: '请选择', trigger: 'change' }],
  leadDeptId: [{ required: true, message: '请选择', trigger: 'change' }],
  source: [{ required: true, message: '请选择', trigger: 'change' }],
  time: [{ required: true, message: '请选择', trigger: 'change' }],
  riskType: [{ required: true, message: '请选择', trigger: 'change' }],
  sorgId: [{ required: true, message: '请选择', trigger: 'change' }]
})

const save = () => {
  clear()
  formVisible.value = true
}

const formCancel = () => {
  formVisible.value = false
}

const show = (sorgRiskHandleId) => {
  clear()
  if (sorgRiskHandleId > 0) {
    form.sorgRiskHandleId = sorgRiskHandleId
    handlerDetail({ sorgRiskHandleId }).then((res) => {
      if (Array.isArray(res.data.files) && res.data.files.length > 0) {
        form.files = res.data.files.map((i) => ({
          fileSum: i.filePage,
          isSave: true,
          name: i.fileName,
          createdAt: dateFormat(i.createTime, 'YYYY-MM-DD'),
          time: i.createTime,
          timestamp: i.createTime,
          isAdd: true,
          file: [
            {
              name: i.fileName,
              status: 'success',
              url: i.fileUrl
            }
          ]
        }))
      } else {
        form.files = []
      }
      form.taskName = res.data.taskName
      form.leadDeptId = res.data.leadDeptId
      form.source = res.data.source
      form.respDeptId = res.data.respDeptId
      form.time = [res.data.startTime, res.data.endTime]
      form.riskType = res.data.riskType
      form.remark = res.data.remark
      form.sorgId = res.data.sorgId
      getType(res.data.sorgId).then((res) => {
        if (res.data === 0) {
          riskTypeOptions.value = riskTypeOptionsObj.value.riskMingBan
        } else {
          riskTypeOptions.value = riskTypeOptionsObj.value.riskSheTuan
        }
      })
    })
  }
  formVisible.value = true
}

const loading = ref(false)
const ruleFormRef = ref()
const submitForm = () => {
  console.log('form', form)
  ruleFormRef.value.validate((valid) => {
    if (!valid) return
    let files = form.files
      .filter((i) => i.isSave)
      .map((i) => {
        let file = {
          fileName: i.name,
          filePage: i.fileSum,
          fileUrl: '',
          createTime: i?.isAdd ? i.time : i.timestamp
        }
        if (Array.isArray(i.file) && i.file.length > 0) {
          //上传了文件
          file.fileName = i.name
          file.fileUrl = i.file[0].url
        }
        return file
      })
    let respDeptName = ''
    if (form.respDeptId) {
      respDeptName = tree.value[form.respDeptId].label
    }
    let startTime = ''
    let endTime = ''
    if (form.time) {
      startTime = form.time[0]
      endTime = form.time[1]
    }
    let sorgName = riskNameOptions.value.find(
      (i) => i.value === form.sorgId
    ).label

    let data = {
      ...form,
      files,
      leadDeptName: tree.value[form.leadDeptId].label,
      respDeptName,
      riskLevel: riskTypeOptions.value.find((i) => i.value === form.riskType)
        .riskLevel,
      startTime,
      endTime,
      sorgName
    }
    delete data.time
    loading.value = true
    let http = form?.sorgRiskHandleId ? handlerUpd : handlerAdd
    http(data)
      .then((res) => {
        ElMessage.success(form.sorgRiskHandleId ? '编辑成功' : '提交成功')
        back()
        emit('reload')
      })
      .finally(() => {
        loading.value = false
      })
  })
}

// 取消
function cancel() {
  ElMessageBox.confirm('确定进行取消操作？', '温馨提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(() => {
      back()
    })
    .catch(() => {})
}

const back = () => {
  formVisible.value = false
}

const clear = () => {
  form.files = []
  form.taskName = undefined
  form.leadDeptId = undefined
  form.source = undefined
  form.respDeptId = undefined
  form.time = undefined
  form.riskType = undefined
  form.remark = undefined
  nextTick(() => {
    ruleFormRef.value.resetFields()
  })
}
defineExpose({ show })
</script>

<style scoped lang="scss">
.search {
  display: flex;
  justify-content: space-between;
}
.btns {
  display: flex;
  justify-content: flex-end;
  align-items: center;
  padding: 10px 0;
}
.select {
  width: 480px;
}
:deep(.el-select-v2) {
  font-size: 16px !important;
}
</style>
